﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace WpfApplication2
{
    /// <summary>
    ///   Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly int _degree;
        private readonly double _dp1PerSec;
        private readonly double _finish;
        private readonly double _horseLength;
        private readonly double _interval;
        private readonly Random _random;

        private Vector _actual1;
        private Vector _actual2;
        private Vector _actual3;

        private double _endbetrag;
        private double _gesamtMichael;
        private double _gesamtSimon;
        private double _gesamtTilli;
        private double _lengthUnit;
        private TimeSpan _time;
        private double _SiegeS;
        private double _SiegeT;
        private double _SiegeM;

        public MainWindow()
        {
            InitializeComponent();
            this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
            _actual1 = VisualTreeHelper.GetOffset(Pferd1);
            _actual2 = VisualTreeHelper.GetOffset(Pferd2);
            _actual3 = VisualTreeHelper.GetOffset(Pferd3);

            _random = new Random();
            _degree = 1;
            _interval = 0.2;
            _horseLength = 100;
            _endbetrag = 1000;
            _finish = 641;
            _time = TimeSpan.FromSeconds(2);

            _gesamtSimon = 0.0;
            _gesamtTilli = 0.0;
            _gesamtMichael = 0.0;
            _SiegeS = 0;
            _SiegeT = 0;
            _SiegeM = 0;

            TB_Eingabe1.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(DeleteTB1), true);
            TB_Eingabe2.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(DeleteTB2), true);
            TB_Eingabe3.AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(DeleteTB3), true);
        }

        private void CalcDistance(out double pferd1, out double pferd2, out double pferd3)
        {
            _lengthUnit = (_finish - _horseLength)/_endbetrag;

            var neubetrag1 = Convert.ToDouble(TB_Eingabe1.Text);
            var neubetrag2 = Convert.ToDouble(TB_Eingabe2.Text);
            var neubetrag3 = Convert.ToDouble(TB_Eingabe3.Text);
            if(neubetrag1 == 0){
                _SiegeS++;
            }
            else if (neubetrag2 == 0)
            {
                _SiegeT++;
            }
            else if (neubetrag3 == 0)
            {
                _SiegeM++;
            }
            
            pferd1 = neubetrag1*_lengthUnit;
            _gesamtSimon += neubetrag1;

            pferd2 = neubetrag2*_lengthUnit;
            _gesamtTilli += neubetrag2;

            pferd3 = neubetrag3*_lengthUnit;
            _gesamtMichael += neubetrag3;


        }
        
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            double dist1;
            double dist2;
            double dist3;

            CalcDistance(out dist1, out dist2, out dist3);


            _actual1 = MoveTo(Pferd1, _actual1, dist1);
            _actual2 = MoveTo(Pferd2, _actual2, dist2);
            _actual3 = MoveTo(Pferd3, _actual3, dist3);

            TB_GesamtS.Text = Convert.ToString((float) _gesamtSimon/100) + "€";
            TB_GesamtT.Text = Convert.ToString((float) _gesamtTilli/100) + "€";
            TB_GesamtM.Text = Convert.ToString((float) _gesamtMichael/100) + "€";

            TB_Eingabe1.Text = "Simon";
            TB_Eingabe2.Text = "Tilli";
            TB_Eingabe3.Text = "Michael";

            TB_SiegeS.Text = Convert.ToString(_SiegeS);
            TB_SiegeT.Text = Convert.ToString(_SiegeT);
            TB_SiegeM.Text = Convert.ToString(_SiegeM);
        }

        private Storyboard CreateStoryBoard(UIElement target, Vector from, Vector to)
        {
            var story = new Storyboard();

            var pathMoveX =
                new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.X)");
            var pathMoveY =
                new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[1].(TranslateTransform.Y)");
            var pathRot =
                new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[0].(RotateTransform.Angle)");

            var rotate = CreateRotateAnimation(TimeSpan.FromSeconds(4*_interval), _degree, _interval);
            //var aniY = new DoubleAnimation(from.Y, to.Y, time);
            var aniX = new DoubleAnimation(from.X, to.X, _time) { AccelerationRatio = _random.NextDouble() };
            aniX.DecelerationRatio = 1 - aniX.AccelerationRatio;

            story.Children.Add(rotate);
            story.Children.Add(aniX);
            //story.Children.Add(aniY);

            Storyboard.SetTarget(aniX, target);
            //Storyboard.SetTarget(aniY, Pferd);
            Storyboard.SetTarget(rotate, target);
            Storyboard.SetTargetProperty(rotate, pathRot);
            Storyboard.SetTargetProperty(aniX, pathMoveX);
            //Storyboard.SetTargetProperty(aniY, pathMoveY);

            story.Duration = _time;

            return story;
        }

        private DoubleAnimationUsingKeyFrames CreateRotateAnimation(TimeSpan time, int degree, double interval)
        {
            var rotate = new DoubleAnimationUsingKeyFrames();
            var frame1 = new LinearDoubleKeyFrame {KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0};
            var frame2 = new LinearDoubleKeyFrame
                {KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(1*interval)), Value = degree};
            var frame3 = new LinearDoubleKeyFrame
                {KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2*interval)), Value = -degree};
            var frame4 = new LinearDoubleKeyFrame
                {KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3*interval)), Value = 0};

            rotate.KeyFrames.Add(frame1);
            rotate.KeyFrames.Add(frame2);
            rotate.KeyFrames.Add(frame3);
            rotate.KeyFrames.Add(frame4);
            rotate.Duration = new Duration(time);
            rotate.RepeatBehavior = RepeatBehavior.Forever;

            return rotate;
        }

        private TransformGroup CreateTransformGrp(Vector center)
        {
            var grp = new TransformGroup();
            var rotate = new RotateTransform {CenterX = 50, CenterY = 50};

            var trans = new TranslateTransform();
            grp.Children.Add(rotate);
            grp.Children.Add(trans);


            return grp;
        }

        public Vector MoveTo(UIElement target, Vector from, double distance, Action completed = null)
        {
            target.RenderTransform = CreateTransformGrp(from);

            var to = new Vector(from.X + distance, from.Y);
            var story = CreateStoryBoard(target, from, to);

            if (completed != null) story.Completed += (o, e) => completed();

            story.Begin();
            return to;
        }

        //private Point CalcPos(UIElement target, double x, double y)
        //{
        //    var offsetX = ((Image) target).Width/2.0;
        //    var offsetY = ((Image) target).Height/2.0;
        //    return new Point(x + offsetX, y + offsetY);
        //}

        private void DeleteTB1(object sender, MouseButtonEventArgs e)
        {
            String Simon = "Simon";
            if (String.Equals(TB_Eingabe1.Text, Simon))
            {
                TB_Eingabe1.Text = "";
            }
        }

        private void DeleteTB2(object sender, MouseButtonEventArgs e)
        {
            String Tilli = "Tilli";
            if (String.Equals(TB_Eingabe2.Text, Tilli))
            {
                TB_Eingabe2.Text = "";
            }
        }

        private void DeleteTB3(object sender, MouseButtonEventArgs e)
        {
            String Michael = "Michael";
            if (String.Equals(TB_Eingabe3.Text, Michael))
            {
                TB_Eingabe3.Text = "";
            }
        }

        private void EmptyTB1(object sender, EventArgs e)
        {
            TB_Eingabe1.Text = "Simon";
        }

        private void TB_Eingabe1_LostFocus(object sender, RoutedEventArgs e)
        {
            if (String.Equals(TB_Eingabe1.Text, ""))
            {
                TB_Eingabe1.Text = "Simon";
            }
        }

        private void TB_Eingabe2_LostFocus(object sender, RoutedEventArgs e)
        {
            if (String.Equals(TB_Eingabe2.Text, ""))
            {
                TB_Eingabe2.Text = "Tilli";
            }
        }

        private void TB_Eingabe3_LostFocus(object sender, RoutedEventArgs e)
        {
            if (String.Equals(TB_Eingabe3.Text, ""))
            {
                TB_Eingabe3.Text = "Michael";
            }
        }

        private void Select_StopLoss10(object sender, RoutedEventArgs e)
        {
            _endbetrag = 1000;
        }

        private void Select_StopLoss15(object sender, RoutedEventArgs e)
        {
            _endbetrag = 1500;
        }

        private void Select_StopLoss20(object sender, RoutedEventArgs e)
        {
            _endbetrag = 2000;
        }

        private void ZahlEingabeTB_Eingabe1(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
            {
                e.Handled = true;
            }
        }

        private void ZahlEingabeTB_Eingabe2(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
            {
                e.Handled = true;
            }
        }

        private void ZahlEingabeTB_Eingabe3(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
            {
                e.Handled = true;
            }
        }
        void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string errorMessage = string.Format("An unhandled exception occurred: {0}", e.Exception.Message);
            MessageBox.Show(errorMessage, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            e.Handled = true;
        }

    }
}